﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using LibraryONTrack.dao;
using LibraryONTrack.Utility;

namespace LibraryONTrack.UI
{

	public partial class MainForm : SMS.Windows.Forms.WizardForm
	{

		public MainForm()
		{
			InitializeComponent();

			Control[] wizard = new Control[] {
		        new WelcomePage(),
		        new AddBookPage(),
		        new AgeNoticesPage(),
		        new PrintNoticesPage()
		        };
			
			Controls.AddRange(wizard);
		}

		private void MainForm_Shown(object sender, EventArgs e)
		{
			// This strips off the exe name 
			String fullAppPath = Path.GetDirectoryName(Application.ExecutablePath);

			SqlDao dao = new SqlDao(Path.Combine(fullAppPath, "lotDb"), true);

			try
			{
				//File.Delete(Path.Combine(fullAppPath, "lotDb.s3db"));
				dao.CheckDB();

			}
			catch (SqlDaoException ex)
			{
				using (DatabaseCorruptDialog dlg = new DatabaseCorruptDialog(ex.Message))
				{
					if (dlg.ShowDialog(this) == DialogResult.Cancel)
					{
						Application.Exit();
					}

					if (dlg.RecoveryAction == RecoveryAction.EraseDatabase)
					{
						if (MessageBoxEx.Show(this,
																"Are you sure you want to proceed with creating a new database?\n\nIMPORTANT: Any existing data will be permanently lost!",
																"Create New Database",
																MessageBoxButtons.OKCancel,
																MessageBoxIcon.Stop,
																MessageBoxDefaultButton.Button2) == DialogResult.OK)
						{

							try
							{
								this.m_nextButton.Enabled = false;
								this.AdminButton.Enabled = false;
								this.m_cancelButton.Enabled = false;

								// Step 1: Initialize Primary Database
								dao.InitializeDB(dlg.InstallSampleData);

								MessageBoxEx.Show("The database has been successfully created");
							}
							finally
							{
								this.m_nextButton.Enabled = true;
								this.AdminButton.Enabled = true;
								this.m_cancelButton.Enabled = true;
							}

						}
					}
					else
					{
						// Do Recovery
					}
				}
			}

		}
	}
}
